package com.wn;

import com.wn.entity.Student;
import org.elasticsearch.index.query.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yellow Docter
 * @date 2023 -03-03
 * @desc * 1、QueryBuilders构建 查询条件
 * * 2、通过查询条件构建本地查询 NativeSearchQuery
 * * 3、调用search方法解析查询结果
 */
@SpringBootTest
public class EsTest03 {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 条件范围搜索
     */
    @Test
    public void demo01() {
        QueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age").gte(20).lte(30);
        Query query = new NativeSearchQuery(rangeQueryBuilder);
        SearchHits<Student> search = elasticsearchRestTemplate.search(query, Student.class);
        extracted(search);

    }

    /**
     * 逻辑搜索
     */
    @Test
    public void demo02() {

        //逻辑   should()  或者  must() 与
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        List<QueryBuilder> list = new ArrayList<>();
        //和 某个字段进行比较
        QueryBuilder builder1 = QueryBuilders.matchQuery("name", "张无忌");
        QueryBuilder builder2 = QueryBuilders.rangeQuery("age").gte(24);
        list.add(builder1);
        list.add(builder2);
        boolQueryBuilder.should().addAll(list);
        Query query = new NativeSearchQuery(boolQueryBuilder);
        SearchHits<Student> searchHits = elasticsearchRestTemplate.search(query, Student.class);
        extracted(searchHits);

    }

    /**
     * 分页搜索
     */
    @Test
    public void demo03() {

        //构建查询
        QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
        Query query = new NativeSearchQuery(queryBuilder);

        //排序
//        query.addSort(Sort.by(Sort.DEFAULT_DIRECTION));  //asc 升序
        query.addSort(Sort.by(Sort.Direction.DESC,"age"));  //desc 降序
        //设置分页
        query.setPageable(PageRequest.of(1,3));

        SearchHits<Student> searchHits = elasticsearchRestTemplate.search(query, Student.class);

        extracted(searchHits);

    }


    private void extracted(SearchHits<Student> searchHits) {
        List<SearchHit<Student>> hits = searchHits.getSearchHits();
        System.out.println("hits = " + hits);
        //拿到每一个hits下面的  _source 下面的 数据
        hits.forEach(hit -> System.out.println("hit = " + hit.getContent()));
    }
}
